package com.witframework.core;

import java.io.File;
import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.jci.listeners.FileChangeListener;
import org.apache.commons.jci.monitor.FilesystemAlterationListener;
import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.witutil.generator.JavaCompilerTools;
import com.witutil.generator.PreferencesConstants;

public class SourceListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent arg0) {
		
	}

	public void contextInitialized(ServletContextEvent arg0) {
		new ReloadingResource().run();		
	}
	public static void main(String[] args) {
        new ReloadingResource().run();
    }
}

/**
 * 检测应用程序目录下的文件变化，并编译已改变的java源文件或在application.properties在更新后重新加载。
 * @author wuxinyang
 *
 */
class ReloadingResource {

	private static Log log = LogFactory.getLog(ReloadingResource.class);

	private final FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();

    public void run() {
    	final URL url=ReloadingResource.class.getResource(PreferencesConstants.BASE_APPLICATION_JAVA_PATH);
		final String basepath=url.getPath();
         log.info("开始检测应用程序目录： " + basepath);
         final FilesystemAlterationListener listener = new FileChangeListener() {
            @Override
			public void onFileChange( final File pFile ) {
            	if(pFile.getName().endsWith(".java")){
            		//log.info("检测到JAVA源文件发生改变.");
            		JavaCompilerTools.run(pFile.getAbsolutePath());
            	}
            	if(pFile.getName().endsWith(".properties")){
            		//检测application.properties在更新后自动加载
            		log.info("find application.properties changed.");
            		ApplicationProperties.reload();
            	}
            }
	        @Override
			public void onFileCreate( final File pFile) {
	        	if(pFile.getName().endsWith(".java")){
	        		log.info("检测到新的JAVA源文件.");
	        		JavaCompilerTools.run(pFile.getAbsolutePath());
	        	}
	        }

	        /**
	         * 在删除java原文件件时删除对应的class文件
	         */
	        @Override
			public void onFileDelete( final File pFile ) {
	        	if(pFile.getName().endsWith(".java")){
            		File deleteClass=new File(pFile.getAbsolutePath().replace(".java",".class"));
            		deleteClass.delete();
            		log.info("删除文件："+deleteClass.getAbsolutePath());
            	}
	        }

         };

        fam.addListener(new File(basepath), listener);
		fam.start();
        
      }

   
}
